﻿using MediatR;
using ThreeTeams.API.Application.Command.BoxTypeManageMentCommand;
using ThreeTeams.Domain;
using ThreeTeams.ErrorCode;
using ThreeTeams.Infrastructure;

namespace ThreeTeams.API.Application.CommandHandler.BoxTypeManageMentCommandHandler
{
    public class GetBoxTypeCommandHandler : IRequestHandler<GetBoxTypeCommand, ApiResult<ApiPaging<BoxType>>>
    {
        private readonly IBaseRepository<BoxType> baseRepository;

        public GetBoxTypeCommandHandler(IBaseRepository<BoxType> baseRepository)
        {
            this.baseRepository = baseRepository;
            // Constructor logic if needed
        }
        public Task<ApiResult<ApiPaging<BoxType>>> Handle(GetBoxTypeCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<ApiPaging<BoxType>>();
            var query = baseRepository.GetAll();
            var totalCount = query.Count();
            var pageSize = request.PageSize > 0 ? request.PageSize : 5;
            var pageIndex = request.PageIndex > 0 ? request.PageIndex : 1;
            var totalPage = (int)Math.Ceiling(totalCount / (double)pageSize);
            var boxTypeList = query.OrderByDescending(a=>a.Id). Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            var pagingData = new ApiPaging<BoxType>
            {
                Data = boxTypeList,
                TotalCount = totalCount,
                TotalPage = totalPage
            };

            result.Code = ApiEnum.Ok;
            result.Data = pagingData;

            return Task.FromResult(result);
        }
    }
}
